import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class L216 {

    public static void main(String[] args) {
        List<List<Integer>> lists = new Solution().combinationSum3(3, 9);
        for (List<Integer> integers : lists) {
            System.out.println(integers.toString());
        }

    }

    static class Solution {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> node = new LinkedList<>();

        public List<List<Integer>> combinationSum3(int k, int n) {
            backTracking(k, n, 1);
            return result;
        }

        private void backTracking(int k, int n, int i) {
            if (node.size() == k) {
                int sum = 0;
                for (Integer integer : node) {
                    sum += integer;
                }
                if (sum == n) {
                    result.add(new LinkedList<>(node));
                }
                return;
            }

            for (int j = i; j <= 9; j++) {
                node.add(j);
                backTracking(k, n, j + 1);
                node.removeLast();
            }
        }
    }
}
